package com.autumn.platform.core.logger.impl;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.slf4j.event.Level;

import com.autumn.platform.core.Utils;
import com.autumn.platform.core.logger.LogLevelUpdater;

public class Log4j2LevelUpdater implements LogLevelUpdater {

    @Override
    public void update(String prefix, Level level) {
        boolean noPrefix = Utils.isBlank(prefix);
        Collection<Logger> notCurrentLoggerCollection = LoggerContext.getContext(false).getLoggers();
        Collection<Logger> currentLoggerCollection = LoggerContext.getContext().getLoggers();
        Collection<Logger> loggerCollection = notCurrentLoggerCollection;
        loggerCollection.addAll(currentLoggerCollection);
        org.apache.logging.log4j.Level newLevel = convertLevel(level);
        for (Logger logger : loggerCollection) {
            if (noPrefix || logger.getName().startsWith(prefix)) {
                logger.setLevel(newLevel);
            }
        }
    }

    @Override
    public void set(String name, Level level) {
        try {
            org.apache.logging.log4j.Level newLevel = this.convertLevel(level);
            LoggerContext.getContext(false).getLogger(name).setLevel(newLevel);
            LoggerContext.getContext().getLogger(name).setLevel(newLevel);
        } catch (Exception e) {
        }
    }

    @Override
    public void setRootLevel(Level level) {
        try {
            org.apache.logging.log4j.Level newLevel = this.convertLevel(level);
            LoggerContext.getContext(false).getRootLogger().setLevel(newLevel);
            LoggerContext.getContext().getRootLogger().setLevel(newLevel);
        } catch (Exception e) {
        }
    }

    @Override
    public Set<String> getLogNames() {
        Collection<Logger> notCurrentLoggerCollection = LoggerContext.getContext(false).getLoggers();
        Collection<Logger> currentLoggerCollection = LoggerContext.getContext().getLoggers();
        Set<String> names = new LinkedHashSet<>();
        for (Logger logger : notCurrentLoggerCollection) {
            names.add(logger.getName());
        }
        for (Logger logger : currentLoggerCollection) {
            names.add(logger.getName());
        }
        return names;
    }

    /**
     * @param level
     * @return
     */
    private org.apache.logging.log4j.Level convertLevel(Level level) {
        org.apache.logging.log4j.Level newLevel = org.apache.logging.log4j.Level.toLevel(level.toString());
        return newLevel;
    }
}
